package com.example.myapplicationndk.h264;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Surface;

public class ScreenShareEncode {

    private static MediaProjectionManager mediaProjectionManager;
    public static int REQUEST_CODE = 102;
    private static MediaProjection mediaProjection;
    private static H264EncodeThread h264EncodeThread;

    // 录屏
    public static void init(Activity activity) {
        mediaProjectionManager = (MediaProjectionManager) activity.getSystemService(Service.MEDIA_PROJECTION_SERVICE);
        Intent intent = mediaProjectionManager.createScreenCaptureIntent();
        activity.startActivityForResult(intent, REQUEST_CODE);
    }


    public static void start(Activity activity, int resultCode, Intent data) {
        Log.d("TAGG", "video start");
        mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
        DisplayMetrics outMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getRealMetrics(outMetrics);
        int widthPixel = outMetrics.widthPixels;
        int heightPixel = outMetrics.heightPixels;
        int width = widthPixel * 2 / 3;
        int height = heightPixel * 2 / 3;
        h264EncodeThread = new H264EncodeThread();

        Surface surface = h264EncodeThread.initMediaCodec(width, height ,null);
        mediaProjection.createVirtualDisplay(
                "screen-h264", //容器的名字
                width, height,
                outMetrics.densityDpi,//像素密度  数组越大 越清晰
                DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC,//设置共享的
                surface,
                new VirtualDisplay.Callback() {
                    @Override
                    public void onPaused() {
                        super.onPaused();
                    }

                    @Override
                    public void onResumed() {
                        super.onResumed();
                    }

                    @Override
                    public void onStopped() {
                        super.onStopped();
                    }
                },//displayCallback,
                null//这里可以设置callback的消息处理线程，为null则在主线程
        );

        h264EncodeThread.startEncode();

    }

    private void stop() {
        if (mediaProjection != null && h264EncodeThread != null) {
            mediaProjection.stop();
            h264EncodeThread.stopEncode();
        }

    }
}
